package com.blb.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 等待和通知案例
 */
public class WaitNotifyDemo2 {

    //创建锁对象
    private static Lock lock = new ReentrantLock();
    //获得条件对象
    private static Condition condition = lock.newCondition();

    public static void testWait(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() +"开始等待");
            //让线程等待
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() +"执行完毕");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                WaitNotifyDemo2.testWait();
            }).start();
        }
        //过5s主线程通知子线程执行
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //通知需要上上锁的代码内执行
        lock.lock();
        try{
            //唤醒所有线程
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}
